package io.wongxd.solution.viewModel

import android.app.Application
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner

internal lateinit var appContext: Application

internal fun setViewModelApplicationContext(context: Application) {
    appContext = context
}

//定义扩展方法
inline fun <reified VM : ViewModel> Fragment.getAppScopeViewModel(): VM {
    return ApplicationScopeViewModelProvider.getApplicationScopeViewModel(VM::class.java)
}

//定义扩展方法
inline fun <reified VM : ViewModel> FragmentActivity.getAppScopeViewModel(): VM {
    return ApplicationScopeViewModelProvider.getApplicationScopeViewModel(VM::class.java)
}

@PublishedApi
internal object ApplicationScopeViewModelProvider : ViewModelStoreOwner {

    private val eventViewModelStore: ViewModelStore = ViewModelStore()

    private val mApplicationProvider: ViewModelProvider by lazy {
        ViewModelProvider(
            ApplicationScopeViewModelProvider,
            ViewModelProvider.AndroidViewModelFactory.getInstance(appContext)
        )
    }

    fun <T : ViewModel> getApplicationScopeViewModel(modelClass: Class<T>): T {
        return mApplicationProvider.get(modelClass)
    }

    override val viewModelStore: ViewModelStore
        get() = eventViewModelStore
}
